import Vue from 'vue'
import Vuex from 'vuex'
import { getStorage, setStorage } from '@/utils/storage.js'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 刷新页面时 从本地存储获取token值、搜索历史、用户头像
    token: getStorage('toutiaoToken') || '',
    SearchHistory: JSON.parse(getStorage('TTSearchHistory')) || [], // 搜索历史
    userphoto: getStorage('UserPhoto') || '', // 用户头像
    username: getStorage('UserName') || '', // 用户名称
  },
  getters: {},
  mutations: {
    setToken(state, val) {
      // 先更新vuex里的token值
      state.token = val
      // 再更新本地存储的值 使每次刷新页面时 都能拿到最新的值
      setStorage('toutiaoToken', val)
    },
    SetSearchHistory(state, val) {
      if (val === '') {
        state.SearchHistory = []
      } else {
        const findResult = state.SearchHistory.includes(val)
        if (findResult) return false
        state.SearchHistory.push(val)
      }

      setStorage('TTSearchHistory', JSON.stringify(state.SearchHistory))
    },
    setUserPhoto(state, val) {
      state.userphoto = val
      setStorage('UserPhoto', val)
    },
    setUserName(state, val) {
      state.username = val
      setStorage('UserName', val)
    },
  },
  actions: {},
  modules: {},
})
